package bot

import (
	"bufio"
	"io"
	"math/rand"
	"net/http"
	"os"
	"time"

	"github.com/sirupsen/logrus"
	logger "github.com/sirupsen/logrus"
)

type ChatHandler struct {
	currentProgramNumber int
}

func NewChatHandler() *ChatHandler {
	return &ChatHandler{currentProgramNumber: 0}
}

func (chat *ChatHandler) Sleep() int {
	logger.Info("=== sleep started ")
	r := rand.Intn(3) + 2
	time.Sleep(time.Duration(r) * time.Second)
	logger.Info("=== sleep started ")
	return r
}

func (chat *ChatHandler) OpenChat(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		inputFile := "webserver/assets/bot/chat/chat_getOpenChat_empty.json"
		if chat.currentProgramNumber%2 == 0 {
			inputFile = "webserver/assets/bot/chat/chat_getOpenChat.json"
		} else {
		}

		r.ParseForm()
		sid := r.Form.Get("sessionId")
		logrus.Debug("openChat sessionId: ", sid)
		inputReader, error := os.Open(inputFile)
		if error != nil {
			logger.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			io.Copy(w, inputReader)
		}
	}
	chat.currentProgramNumber++
}
